package net.jiastudy.web.config;

import java.io.Serializable;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;

import net.jiastudy.biz.user.entity.User;
import net.jiastudy.biz.user.service.UserService;

@Configuration
public class CustomPermissionEvaluator implements PermissionEvaluator {
	
	@SuppressWarnings("unused")
	private final Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private UserService userService;

	@Override
	public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
		UserDetails ud = (UserDetails) authentication.getPrincipal();
		User user = userService.getUserByUsername(ud.getUsername());
		if (user.isAdmin()) {
			return true;
		}
		Set<String> permissions = userService.findPermissionCodesByUserId(user.getId());
		return permissions.contains(targetDomainObject.toString() + ":" + permission.toString());
	}

	@Override
	public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType,
			Object permission) {
        return false;
	}
}
